package com.example.permission.config;

import com.example.permission.service.UserService;
import com.example.permission.service.RoleService;
import com.example.permission.service.impl.UserServiceImpl;
import com.example.permission.service.impl.RoleServiceImpl;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import org.apache.ibatis.session.SqlSessionFactory;

@WebListener
public class MyBatisConfig implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        SqlSessionFactory sqlSessionFactory = DatabaseConfig.getSqlSessionFactory();

        // 初始化服务
        UserService userService = new UserServiceImpl(sqlSessionFactory);
        RoleService roleService = new RoleServiceImpl(sqlSessionFactory);

        // 将服务设置到ServletContext中
        context.setAttribute("userService", userService);
        context.setAttribute("roleService", roleService);

        System.out.println("MyBatis and Services initialized successfully.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Application shutdown.");
    }
}